package com.zhourh.bang.modular.edu.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.zhourh.bang.common.persistence.dao.SResultMapper;
import com.zhourh.bang.common.persistence.model.SResult;
import com.zhourh.bang.common.support.Response;
import com.zhourh.bang.core.util.ToolUtil;
import com.zhourh.bang.modular.edu.service.IScoreService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import weka.associations.Apriori;
import weka.core.Instances;

import javax.annotation.Resource;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/cal")
public class CalController {

    private String PREFIX = "/edu/cal/";

    @Resource
    private SResultMapper resultMapper;

    @Resource
    private IScoreService scoreService;

    @RequestMapping("")
    public String index() {
        return PREFIX + "cal.html";
    }

    @RequestMapping("genFile")
    @ResponseBody
    public Object genFile(String fileName, String rule, Integer minRangeNum) {
        return this.scoreService.genFormatFile(fileName, rule, minRangeNum);
    }

    @RequestMapping("viewFile")
    @ResponseBody
    public Object viewFile(String filePath) {
        if (!ToolUtil.isOneEmpty(filePath)) {
            return FileUtil.readLines(new File(filePath), "GBK");
        }
        return null;
    }

    @RequestMapping("digData")
    @ResponseBody
    public Object digData(String filePath, Double minSupport, Double maxSupport, Double peakValue,
                          Double minMetric, Double delta, Double subjectValue, Integer resultNum, Boolean isPro) {
        System.out.println(filePath);
        if (ToolUtil.isNotEmpty(filePath) && (new File(filePath).exists())) {
            long timeStart = System.currentTimeMillis();
            Instances data = null;
            try {
                BufferedReader reader = new BufferedReader(new FileReader(filePath));
                data = new Instances(reader);
                data.setClassIndex(data.numAttributes() - 1);
                reader.close();
            } catch (FileNotFoundException e) {
                System.out.println("读取文件错误");
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
//            double lowerBoundMinSupportValue = 0.1;
//            double minMetricValue = 0.98; //置信度
//            double deltaValue = 0.01;
            int numRulesValue = resultNum != null && resultNum != 0 ? resultNum : 100;
            double upperBoundMinSupportValue = 0.9;
            String resultapriori;

            Apriori apriori = new Apriori(isPro);
            apriori.setPeakValue(peakValue);
            apriori.setLowerBoundMinSupport(minSupport);//最小支持度下限
            apriori.setUpperBoundMinSupport(maxSupport);//最小支持度上限
            apriori.setDelta(delta);//支持度增量
            apriori.setMinMetric(minMetric);//最小置信度
            apriori.setNumRules(numRulesValue);//
            try {
                apriori.buildAssociations(data);
            } catch (Exception e) {
                e.printStackTrace();
            }
            resultapriori = apriori.toString();
//            System.out.println(resultapriori);
            Map<String, Object> result = new HashMap<>();
            long duration = System.currentTimeMillis() - timeStart;
            result.put("duration", duration);
            result.put("data", resultapriori.replaceAll("\\n", "<br/>"));
            //计算lift大于1的个数
            int count4lift = 0;
            String regex = "(lift:)\\((\\S+)\\)";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(resultapriori);
            List<String> list = new ArrayList<>();
            while (matcher.find()) {
                String lift = matcher.group();
                if (lift != null) {
                    String value = lift.substring(lift.indexOf("(")+1, lift.indexOf(")"));
//                    System.out.println(lift + " - " + value);
                    if(Double.valueOf(value)>1){
                        count4lift++;
                    }
                }
                list.add(lift);
            }
            result.put("count4lift",count4lift);
//            System.out.println("count : " + count4lift);
            return result;

        }
        return "找不到ARFF属性文件";
    }


    @RequestMapping("saveData")
    @ResponseBody Response saveData(String rule,String content){
        System.out.println(rule);
        System.out.println(content);
        if(StrUtil.isNotEmpty(content)){
            String main = content.substring(content.indexOf("Best rules found:")+29);
            if(StrUtil.isNotEmpty(main)){
                String[] lines = main.split("<br/>");
                if(lines.length>0){
                    //插入新数据先删除原有数据
                    resultMapper.delete(null);
                    //循环插入新数据
                    for (String line : lines){
                        System.out.println(line);
                        String prev = line.substring(line.indexOf(".")+1,line.indexOf("==>"));
                        String next = line.substring(line.indexOf("==>")+3,line.indexOf("<conf:"));
                        String prop = line.substring(line.indexOf("lift:"));
                        SResult sResult = new SResult();
                        sResult.setPrev(prev.trim());
                        sResult.setNext(next.trim());
                        sResult.setRule(rule.trim());
                        sResult.setPropValue(prop.trim());
                        sResult.insert();
                    }
                }
            }
        }
        return Response.success();
    }
}
